#include <stdbool.h>
#include <stddef.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/shm.h>

#include "shared_memory.h"

void inno_log_error(const char *cmd_fmt, ...) {
}

void inno_log_info(const char *cmd_fmt, ...) {
}

// Function to create shared memory
bool shared_memory_create(SharedMemory *shm, const char *shm_path, int32_t proj_id, uint32_t shm_size) {
  shm->shm_id = -1;
  shm->shm_addr = NULL;
  bool return_value = false;

  key_t key = ftok(shm_path, proj_id);
  if (key == -1) {
    return_value = false;
  } else {
    uint32_t shmflag = (uint32_t)O_RDWR | (uint32_t)O_CREAT;
    shm->shm_id = shmget(key, shm_size, (int32_t)shmflag);
    if (shm->shm_id < 0) {
      (void)inno_log_error("shmget %d", (const void *)(intptr_t)shm->shm_id);
      return_value = false;
    } else {
      shm->shm_addr = shmat(shm->shm_id, NULL, 0);
      if (shm->shm_addr == MAP_FAILED) {
        (void)inno_log_error("shmat %p", (const void *)shm->shm_addr);
        return_value = false;
      } else {
        return_value = true;
      }
    }
  }

  return return_value;
}

// Function to destroy shared memory
void shared_memory_destroy(const SharedMemory *shm) {
  if (shm->shm_addr != NULL) {
    const void *tmp_addr = (const void *)shm->shm_addr;
    if (shmdt(tmp_addr) < 0) {
      (void)inno_log_error("shmdt %p", (const void *)shm->shm_addr);
    }
  }
}

int32_t main(void) {
  SharedMemory shm;
  const char *shm_path = "/tmp";    // Example path
  int32_t proj_id = 1234;           // Example project ID
  uint32_t shm_size = 1024;         // Example shared memory size
  int32_t p_ret = 0;

  if (shared_memory_create(&shm, shm_path, proj_id, shm_size)) {
    (void)inno_log_info("Shared memory created successfully!\n");

    if (shm.shm_addr != NULL) {
      // Use shm.shm_addr for shared memory operations
      // ...
    }

    (void)shared_memory_destroy(&shm);
    (void)inno_log_info("Shared memory destroyed!\n");
  } else {
    (void)inno_log_error("Failed to create shared memory.\n");
  }

  return 0;
}
